package com.example.study.page.fragment

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.os.RemoteException
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.study.databinding.FragmentMessengerServiceBinding
import com.example.study.page.service.MessengerService

class MessengerServiceFragment : Fragment() {
    private lateinit var binding: FragmentMessengerServiceBinding
    private var mService: Messenger? = null
    private var mIsBound: Boolean? = false

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentMessengerServiceBinding.inflate(layoutInflater, container, false)
        binding.btnBind.setOnClickListener {
            doBindService()
        }
        binding.btnUnbind.setOnClickListener {
            doUnbindService()
        }
        binding.btnSend.setOnClickListener {
            mService?.send(Message.obtain(null, MessengerService.MSG_SET_VALUE, 100, 0))
        }
        return binding.root
    }


    inner class IncomingHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MessengerService.MSG_SET_VALUE -> {
                    binding.text.text = msg.arg1.toString()
                }

                else -> {
                    super.handleMessage(msg)
                }
            }
        }
    }

    val mMessenger = Messenger(IncomingHandler(Looper.getMainLooper()))

    private val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            mService = Messenger(service)
            binding.text.text = "Bind."
            try {
                val msg = Message.obtain(null, MessengerService.MSG_REGISTER_CLIENT)
                msg.replyTo = mMessenger
                mService?.send(msg)
            } catch (e: RemoteException) {

            }
            Toast.makeText(context, "绑定成功", Toast.LENGTH_SHORT).show()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            mService = null
            binding.text.text = "Unbind."
            Toast.makeText(context, "断开连接", Toast.LENGTH_SHORT).show()
        }

    }

    private fun doBindService() {
        val intent = Intent(context, MessengerService::class.java)
        activity?.bindService(intent, connection, Context.BIND_AUTO_CREATE)
        mIsBound = true
        binding.text.text = "Binding."
    }

    private fun doUnbindService() {
        if (mIsBound!!) {
            try {
                val msg = Message.obtain(null, MessengerService.MSG_UNREGISTER_CLIENT)
                msg.replyTo = mMessenger
                mService?.send(msg)
            } catch (e: RemoteException) {

            }
            activity?.unbindService(connection)
            mIsBound = false
            binding.text.text = "Unbinding."
        }
    }
}